package com.dx.mes.service.webservice.Controller;
/**
 * WatchDog for Equipment Loader Port (DCS Automation)
 */

import com.dx.mes.common.core.base.service.ICIMBaseInterface;
import com.dx.mes.common.core.rabbitmq.BaseConnFactory;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

@Controller("exfrController")
public class ErpxfrController{
	private LogUtils logUtils;
	@Resource
	private ApplicationContext context;
	@Resource
	private BaseConnFactory baseConnFactory;

	@PostConstruct
	//监听ERP的Q信息
	public void loadErpTransferProc() throws IOException{
		logUtils = new LogUtils(ErpxfrController.class);
		//创建连接
		Connection connection = baseConnFactory.creatConnectionFactory().newConnection();
		/**
		 * 在配置档properties文件中找到Qname & service的名字
		 */
		Properties props = new Properties();
		try {
			props.load(ErpxfrController.class.getResourceAsStream("/mq.properties"));
		} catch (IOException e) {
			logUtils.error("Read mq.properties configuration error");
			e.printStackTrace();
			logUtils.error(e.toString());
		}
		
		/**
		 * 根据properties文件创建consumer连接
		 */
		Iterator<Entry<Object, Object>> it = props.entrySet().iterator();  
        while (it.hasNext()) {  
            Entry<Object, Object> entry = it.next();  
            String mqName = entry.getKey().toString();  
            String beanName = entry.getValue().toString();  
            try {
                final Channel channel = connection.createChannel();
				channel.queueDeclare(mqName, true, false, false, null);
                channel.basicQos(1);
                
                logUtils.info("等待接受" + mqName + "消息....");
                
                channel.basicConsume(mqName, false, new DefaultConsumer(channel) {
                	@Override
                	public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
                		
                        String response = "";
                        try {
                            String inTrx = new String(body,"UTF-8");
                            logUtils.info("consumer 接收" + mqName + "的消息是：" + inTrx);
                            
                            String evt_no = GUIDGenerator.javaGUID();
                            ICIMBaseInterface icimBaseinterFace = (ICIMBaseInterface) context.getBean(beanName);
							response = icimBaseinterFace.subMainProc(evt_no,inTrx);
							logUtils.info("consumer 发送" + mqName + "的消息是：" + response);
							/*if(StringUtils.isEmpty(response) || response.indexOf(RETURN_CODE_OK) == -1){//失败放入Error Q后续处理
								baseConnFactory.addSAPREQProc(mqName + ".ERR", inTrx);
							}*/
                        } catch (Exception e) {
                        	logUtils.error(Util.stackTraceToString(e));
                        } finally {
                        	channel.basicAck(envelope.getDeliveryTag(), false);
                        }
                    }
                });
            } catch (Exception e) {
            	logUtils.error(Util.stackTraceToString(e));
            }
        }
	}
}
